<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;

        }

        body {
            height: 2000px;

        }

        .box {
            position: relative;
            top: 400px;
            left: 600px;
            width: 100px;
            height: 100px;
            background-color: rgb(255, 240, 249);
        }
    </style>
</head>

<body>
    <div class="box"></div>
</body>
<script>
    var box = document.getElementsByClassName('box')[0];
    box.onmousedown = function (e) {
        //计算盒子左上角到边框的距离
        console.log(e.pageX - e.offsetX, e.pageY - e.offsetY)
        //当鼠标点击到图案(box)并保持按压状态时
        // 开始进行onmousemove一直检测
        // 鼠标活动,时刻更box的位置
        // 注意由于时document.的onmousemove所以鼠标全局移动都会检测
        document.onmousemove = function (e1) {
            box.style.top = e1.pageY - e.offsetY + 'px'
            box.style.left = e1.pageX - e.offsetX + 'px'
        }
        //一旦鼠标松开,document.onmouseup 触发,鼠标的全局监测
        // onmousemove事件消除
        document.onmouseup = function (e2) {
            //鼠标松开时
            document.onmousemove = null;
        }
    }

</script>

</html>